/*
 * File: /src/plugins/http.js
 * Project: shop_admin
 * version: 0.1.0
 * Created Date: 2020-11-08 18:48:10
 * Author: Xiaotao
 * -----
 * Last Modified: Sun Nov 08 2020
 * Modified By: xiaotao
 * -----
 * Copyright (c) 2020 Gray Snail
 */

import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

// 导入NProgress, 包对应的JS和CSS
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import { Message } from 'element-ui'

// 配置请求根路径
// 本机地址
axios.defaults.baseURL = 'http://127.0.0.1:8888/api/private/v1/'
// 远程后台地址
// axios.defaults.baseURL = 'https://www.liulongbin.top:8888/api/private/v1/'

// 在request 拦截器中, 展示进度条 NProgress.start()
// 请求在到达服务器之前，先会调用use中的这个回调函数来添加请求头信息
axios.interceptors.request.use(
  config => {
    NProgress.start()
    // console.log(config)
    // 为请求头对象，添加token验证的Authorization字段
    config.headers.Authorization = window.sessionStorage.getItem('token')
    return config
  },
  error => {
    console.log('req', error)
    return Promise.reject(error)
  }
)
// response 拦截器中,  隐藏进度条NProgress.done()
axios.interceptors.response.use(
  config => {
    NProgress.done()
    return config
  },
  error => {
    NProgress.done()
    console.log('axios respone error:', error.message)
    Message.error(error.message)
    return Promise.reject(error)
  }
)

// 挂在到Vue实例，后面可通过this调用
Vue.use(VueAxios, axios)
